package com.xuecheng.system.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LoginDto;
import com.xuecheng.commons.model.vo.LoginVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.JwtUtils;
import com.xuecheng.system.domain.User;
import com.xuecheng.system.mappers.UserMapper;
import com.xuecheng.system.service.UserService;
import com.xuecheng.web.exceptions.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * @author Keson
 * @version 1.0.0
 * @title UserServiceImpl
 * @description 用户业务实现
 * @create 2022/7/14 16:09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    /**
     * @description: 登录校验业务
     * @param: LoginDto(手机号 、 用户密码 、 用户类型)
     * @return: com.xuecheng.commons.model.vo.ResponseResult
     * @author Keson
     * @date: 2022/7/14 16:42
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.判断数据是否为空
        if (StringUtils.isEmpty(dto.getUsername()) ||
                StringUtils.isEmpty(dto.getPassword()) ||
                StringUtils.isEmpty(dto.getUtype())) {
            //生成参数错误异常
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }

        //2.根据手机号和类型判断查询
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone, dto.getUsername());
        qw.eq(User::getUtype, dto.getUtype());
        User user = this.getOne(qw);

        //3.判断用户是否存在
        if (user == null) {
            throw new BusinessException(ErrorCode.LOGINERROR);
        }

        //4.对输入密码加密，进行判断
        dto.setPassword(DigestUtil.md5Hex(dto.getPassword()));
        if (!dto.getPassword().equals(user.getPassword())) {
            throw new BusinessException(ErrorCode.LOGINERROR);
        }

        //5.如果一致，生成token
        HashMap map = new HashMap<>();
        map.put("userId", user.getId());
        map.put("companyId", user.getCompanyId());
        map.put("companyName", user.getCompanyName());

        String token = JwtUtils.createToken(map, 30);

        //6.构造返回
        return ResponseResult.okResult(new LoginVo(token, user.getName()));
    }
}
